<script lang="ts" setup>
import {
  ElButton,
  ElDialog,
  ElInput,
  ElTable,
  ElTableColumn,
  ElDatePicker,
  ElSelect,
  ElOption,
  ElRadioGroup,
  ElRadio,
  type DateModelType
} from 'element-plus'
import { get, orderBy } from 'lodash-es'
import { Promotion } from '@element-plus/icons-vue'
import { getReservationsListApi } from '@/api/reservation'
import { bulkCreateSmsLogsApi, getSmsLogsListBySequenceApi } from '@/api/sms-log'
import { reactive, ref } from 'vue'
import dayjs from 'dayjs'
import { Search, SearchItem } from '@/components/Search'
import { Reservation } from '@/api/reservation/types'
import { SmsLog } from '@/api/sms-log/types'
import { unref } from 'vue'
import { formatDate } from '@/utils'

defineOptions({
  name: 'ReservationIndex'
})

interface Conditions {
  dates: [DateModelType, DateModelType]
  reservationCount: number
  blockCode: string
  companyName: string
  lastName: string
  firstName: string
  confirmNumber: string
  resvNameId: string
  getList: boolean
  roomNumber: string
  resvStatus: string
  resvDisposition: string
  roomClass: string
  includePseudoRoom: boolean
}

const conditions = reactive<Conditions>({
  dates: [dayjs().format('YYYY-MM-DD'), dayjs().format('YYYY-MM-DD')],
  // dates: ['2017-12-09', '2017-12-09'], //
  reservationCount: 100,
  blockCode: '', //
  companyName: '', //
  lastName: '', //
  firstName: '', //
  confirmNumber: '', //
  resvNameId: '',
  getList: true,
  roomNumber: '', //
  resvStatus: 'DUEIN', //
  resvDisposition: 'NONE', //
  roomClass: '',
  includePseudoRoom: false //
})

const data = ref<Reservation[]>([])
const loading = ref(false)
const tableRef = ref<InstanceType<typeof ElTable>>()
const selectedRows = ref<Reservation[]>([])
const smsLogs = ref<SmsLog[]>([])
const smsLogVisible = ref(false)
const smsLogLoading = ref(false)

const RESV_STATUS = [
  { code: 'DUEIN', name: '预抵' },
  { code: 'DUEOUT', name: '预离' },
  { code: 'INHOUSE', name: '在店' },
  { code: 'RESERVED', name: '待到店' },
  { code: 'CHECKEDOUT', name: '离店' },
  { code: 'CANCELED', name: '取消' },
  { code: 'NOSHOW', name: '预订未到' }
]

const getData = async () => {
  loading.value = true
  const res = await getReservationsListApi({
    startDate: conditions.dates[0],
    endDate: conditions.dates[1],
    ...conditions
  }).finally(() => {
    loading.value = false
  })

  data.value = orderBy(
    res.data,
    ['fullName', 'RoomStay.StartDate', 'RoomStay.EndDate'],
    ['asc', 'asc', 'asc']
  )
}

const getPersons = (reservation: Reservation): string => {
  return [
    get(reservation, 'RoomStay.GuestCount.ADULT', 0),
    get(reservation, 'RoomStay.GuestCount.CHILD', 0)
  ].join('/')
}

const sendSMS = async () => {
  loading.value = true
  selectedRows.value = unref(tableRef)?.getSelectionRows()
  const { data } = await bulkCreateSmsLogsApi(selectedRows.value).finally(() => {
    loading.value = false
  })
  smsLogs.value = data
  smsLogVisible.value = true
}

const getSmsLogs = async () => {
  if (smsLogs.value.length > 0) {
    smsLogLoading.value = true
    const { data } = await getSmsLogsListBySequenceApi(smsLogs.value[0].sequence!).finally(() => {
      smsLogLoading.value = false
    })

    smsLogs.value = data
  }
}

getData()
</script>

<template>
  <div v-loading="loading">
    <Search :model="conditions" @reset="getData" @search="getData">
      <SearchItem label="抵店日期" prop="dates">
        <ElDatePicker
          v-model="conditions.dates"
          :clearable="false"
          type="daterange"
          value-format="YYYY-MM-DD"
        />
      </SearchItem>
      <SearchItem label="预订状态">
        <ElSelect v-model="conditions.resvStatus" class="w-full">
          <ElOption
            v-for="item of RESV_STATUS"
            :key="item.code"
            :label="item.name"
            :value="item.code"
          />
        </ElSelect>
      </SearchItem>
      <SearchItem label="姓/名">
        <ElInput v-model="conditions.lastName" class="!w-1/2" clearable maxlength="50" />
        <ElInput v-model="conditions.firstName" class="!w-1/2" clearable maxlength="50" />
      </SearchItem>
      <SearchItem label="押金">
        <ElRadioGroup v-model="conditions.resvDisposition">
          <ElRadio label="''">ALL</ElRadio>
          <ElRadio label="NONE">未支付</ElRadio>
        </ElRadioGroup>
      </SearchItem>
      <SearchItem label="含假房">
        <ElRadioGroup v-model="conditions.includePseudoRoom">
          <ElRadio :label="true">Y</ElRadio>
          <ElRadio :label="false">N</ElRadio>
        </ElRadioGroup>
      </SearchItem>
      <SearchItem label="公司名称" prop="companyName">
        <ElInput v-model="conditions.companyName" clearable maxlength="50" />
      </SearchItem>
      <SearchItem label="团队代码" prop="blockCode">
        <ElInput v-model="conditions.blockCode" clearable maxlength="50" />
      </SearchItem>
      <SearchItem label="确认号" prop="confirmNumber">
        <ElInput v-model="conditions.confirmNumber" clearable maxlength="50" />
      </SearchItem>
      <SearchItem label="房号" prop="roomNumber">
        <ElInput v-model="conditions.roomNumber" clearable maxlength="50" />
      </SearchItem>
      <SearchItem label="查询预订数" prop="reservationCount">
        <ElSelect v-model="conditions.reservationCount" class="w-full">
          <ElOption :value="10" label="10" />
          <ElOption :value="20" label="20" />
          <ElOption :value="50" label="50" />
          <ElOption :value="100" label="100" />
          <ElOption :value="200" label="200" />
          <ElOption :value="500" label="500" />
        </ElSelect>
      </SearchItem>
    </Search>

    <div class="mt-10px bg-white p-20px">
      <div class="mb-10px flex flex-row justify-between">
        <div>列表</div>
        <div class="flex flex-row items-center">
          <ElButton :icon="Promotion" type="primary" @click="sendSMS">发送短信</ElButton>
          <Icon class="mr-8px ml-8px cursor-pointer" icon="ep:refresh-right" />
        </div>
      </div>
    </div>

    <ElTable ref="tableRef" :data="data" stripe>
      <ElTableColumn type="selection" width="55" />

      <ElTableColumn
        label="姓名"
        min-width="140"
        prop="fullName"
        show-overflow-tooltip
        width="auto"
      />

      <ElTableColumn
        label="中文名"
        min-width="140"
        prop="altName"
        show-overflow-tooltip
        width="auto"
      />

      <ElTableColumn label="确认号" prop="confirmNumber" show-overflow-tooltip width="100" />

      <ElTableColumn label="抵店日期" prop="RoomStay.StartDate" show-overflow-tooltip width="120" />

      <ElTableColumn label="离店日期" prop="RoomStay.EndDate" show-overflow-tooltip width="120" />

      <ElTableColumn
        label="状态"
        prop="computedReservationStatus"
        show-overflow-tooltip
        width="120"
      />

      <ElTableColumn label="手机号" prop="PhoneNumber" show-overflow-tooltip width="180" />

      <ElTableColumn
        label="房间"
        prop="RoomStay.RoomType.RoomNumber"
        show-overflow-tooltip
        width="80"
      />

      <ElTableColumn
        label="房型"
        prop="RoomStay.RoomType.roomTypeCode"
        show-overflow-tooltip
        width="80"
      />

      <ElTableColumn
        align="right"
        header-align="right"
        label="人数"
        show-overflow-tooltip
        width="60"
      >
        <template #default="{ row }">
          {{ getPersons(row) }}
        </template>
      </ElTableColumn>

      <ElTableColumn
        align="right"
        header-align="right"
        label="房数"
        prop="RoomStay.RoomType.numberOfUnits"
        show-overflow-tooltip
        width="60"
      />

      <ElTableColumn
        label="聚会代码"
        prop="Miscellaneous.PartyCode"
        show-overflow-tooltip
        width="160"
      />

      <ElTableColumn
        label="团队代码"
        prop="RoomStay.RoomType.invBlockCode"
        show-overflow-tooltip
        width="160"
      />

      <ElTableColumn
        label="价格代码"
        prop="RoomStay.RatePlan.ratePlanCode"
        show-overflow-tooltip
        width="140"
      />

      <ElTableColumn align="right" header-align="right" label="序号" type="index" width="80" />
    </ElTable>

    <ElDialog
      v-model="smsLogVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      draggable
      title="短信发送记录"
      width="1200px"
    >
      <ElTable :data="smsLogs" stripe>
        <ElTableColumn label="确认号" prop="confirm_number" show-overflow-tooltip width="100" />

        <ElTableColumn label="手机号" prop="mobile" show-overflow-tooltip width="160" />

        <ElTableColumn label="短信内容" prop="content" show-overflow-tooltip width="auto" />

        <ElTableColumn label="发送结果" prop="result" show-overflow-tooltip width="100" />

        <ElTableColumn label="发送状态" prop="status" show-overflow-tooltip width="100" />

        <ElTableColumn label="发送时间" show-overflow-tooltip width="160">
          <template #default="{ row }">
            {{ formatDate(row.created_at, 'YYYY-MM-DD HH:mm') }}
          </template>
        </ElTableColumn>

        <ElTableColumn align="right" header-align="right" label="序号" prop="order_by" width="80" />
      </ElTable>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="smsLogVisible = false">关闭</el-button>
          <el-button :loading="smsLogLoading" type="primary" @click="getSmsLogs">刷新</el-button>
        </span>
      </template>
    </ElDialog>
  </div>
</template>
